<script setup lang="ts">
import type {
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadUserFile,
} from 'element-plus';

import { ref } from 'vue';

import { Plus } from '@vben/icons';

import { ElMessage, genFileId } from 'element-plus';
import * as XLSX from 'xlsx';

import { reqInitAll } from '#/api/exchange-center';

const props = defineProps(['platformId']);
const emit = defineEmits(['reload']);
const upload = ref<UploadInstance>();

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

// 数据表格
const dialogTableVisible = ref(false);

interface IAccountRow {
  account: string;
  ip: string;
  key: string;
  secret: string;
  passphrase: string;
  group?: string;
  [key: string]: any;
}
const tableData = ref<IAccountRow[]>([]);
const flag = false;
const onFileChange = (file: UploadUserFile) => {
  // 读取表格
  const fileReader = new FileReader();
  fileReader.addEventListener('load', (ev: Event) => {
    const workbook = XLSX.read((ev.target as FileReader).result, {
      type: 'binary',
    });
    // sheet的名称
    const sheetName = workbook.SheetNames[0];

    const sheet = sheetName && workbook.Sheets[sheetName];
    if (!sheet) {
      console.error('Sheet not found:', sheetName);
      return;
    }
    const sheetData: IAccountRow[] = XLSX.utils.sheet_to_json(sheet);

    flag && dealExcel(sheetData); // 当表头跟参数名不一致时，需要调用dealExcel去映射表头
    tableData.value = sheetData;
    dialogTableVisible.value = true;
  });

  fileReader.readAsBinaryString(file.raw as Blob);
};

function dealExcel(sheetData: IAccountRow[]) {
  const keymap = {
    account: 'account',
    ip: 'ip',
    key: 'key',
    group: 'group',
    secret: 'secret',
    passphrase: 'passphrase',
  };

  sheetData.forEach((sourceObj) => {
    Object.keys(sourceObj).map((keys) => {
      const newKey = keymap[keys as keyof typeof keymap];
      if (newKey) {
        sourceObj[newKey] = sourceObj[keys];
        delete sourceObj[keys];
      }
      return sourceObj;
    });
  });

  tableData.value = sheetData;
  dialogTableVisible.value = true;
}

const submitUpload = async () => {
  dialogTableVisible.value = false;
  // upload.value!.submit();
  const params = {
    platform_id: props.platformId,
    lists: tableData.value,
  };
  try {
    await reqInitAll(params);
    ElMessage({ message: '批量添加成功', type: 'success' });
    emit('reload');
  } catch (error) {
    ElMessage({ message: error.message || '批量添加失败', type: 'success' });
  }
};
</script>

<template>
  <div>
    <el-upload
      ref="upload"
      :limit="1"
      :on-exceed="handleExceed"
      :auto-upload="false"
      :show-file-list="false"
      @change="onFileChange"
    >
      <template #trigger>
        <el-button :icon="Plus" type="primary">批量新增</el-button>
      </template>
    </el-upload>

    <el-dialog v-model="dialogTableVisible" title="批量新增账户" width="800">
      <el-table :data="tableData">
        <el-table-column property="account" label="Account" width="200" />
        <el-table-column property="group" label="Group" />
        <el-table-column property="ip" label="IP" width="150" />
        <el-table-column property="key" label="Key" />
        <el-table-column property="secret" label="Secret" />
        <el-table-column property="passphrase" label="Passphrase" />
      </el-table>
      <template #footer>
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload">确认添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
